package com.apobates.forum.nanus.core;

import com.apobates.forum.nanus.NanusHashStrategy;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 使用BASE64作散列策略
 * @author xiaofanku@live.cn
 * @since 20210827
 */
public class NanusBASE64Strategy implements NanusHashStrategy {

    @Override
    public String encode(String value, String defaultValue) {
        try{
            return Base64.getEncoder().encodeToString(value.getBytes(StandardCharsets.UTF_8.name()));
        }catch(NullPointerException | UnsupportedEncodingException ex){
            return defaultValue;
        }
    }

    @Override
    public String decode(String value, String defaultValue) {
        try {
            byte[] dataBytes = Base64.getDecoder().decode(value);
            return new String(dataBytes, StandardCharsets.UTF_8.name());
        } catch (NullPointerException | UnsupportedEncodingException ex) {
            return defaultValue;
        }
    }
}
